import turbogears as tg
from turbogears import controllers, expose, flash, validators, redirect
from turbogears.widgets import WidgetsList, TableForm, TextField, TextArea, Widget, HiddenField
from turbogears.widgets import AutoCompleteTextField
from turbogears.widgets import DataGrid
from bookloantracker.model import *
import logging
log = logging.getLogger("bookloantracker.bookcadaster")

from cherrypy import session

class BookFormList(WidgetsList):
    bookName=TextField(label=_("Nome"),
                       validator=validators.NotEmpty(),
                       attrs={"size":"70"})
    isbn = TextField(label="ISBN",
                     validator=validators.NotEmpty(),
                     attrs={"size":"70"})
    edition = TextField(label=_("Edition"),
                        attrs={"size":"70"})
    authors = AutoCompleteTextField(label=_("Author(s)"),
                                    search_controller="/acGetAuthor",
                                    search_param="authorName",
                                    result_name="matches",
                                    only_suggest=True,
                                    show_spinner=False,
                                    attrs={"title":_("Comma separeted"),
                                           "size":"70"})
    publisher = AutoCompleteTextField(label=_("Publisher"),
                                      search_controller="/acGetPublisher",
                                      search_param="publisherName",
                                      result_name="matches",
                                      only_suggest=True,
                                      show_spinner=False,
                                      attrs={"size":"70"})
    webPage = TextField(label=_("Home Page"),
                        attrs={"size":"70"})
    wordKeys = AutoCompleteTextField(label=_("Word Keys"),
                                     search_controller="/acGetWordKeys",
                                     search_param="wordKey",
                                     result_name="matches",
                                     only_suggest=True,
                                     show_spinner=False,
                                     attrs={"title":_("Comma separeted"),
                                            "size":"70"})
    description = TextArea(label=_("Description"),
                           rows=4, cols=70)
    localization = TextField(label=_("Localization"),
                             attrs={"size":"70"})
    updateBook = HiddenField()


class BookInfoTable(Widget):
    name="bookInfoTable"
    template = "bookloantracker.templates.bookinfotable"
    params = ["book"]

    def __init__(self, *args, **kw):
        super(BookInfoTable, self).__init__(*args, **kw)


bookForm = TableForm(
    fields = BookFormList(),
    action = "save",
    submit_text=_("Submit")
    )

bookInfoTable = BookInfoTable()

loanHistoryGrid = DataGrid(
    fields = [(_("Loaner"),lambda loan: loan.loaner.name),
              (_("Start"),lambda loan: loan.start.strftime("%d/%m/%Y")),
              (_("End"),lambda loan: loan.stop and loan.stop.strftime("%d/%m/%Y") or "--")]
    )

class BookCadaster(controllers.Controller):
    @expose()
    def default(self, *k, **kw):
        redirect(tg.url("/"))

    @expose(template="bookloantracker.templates.bookcadaster")
    def index(self):
        self.cleanSessionForm()
        return dict(bookForm = bookForm,
                    values={})

    @expose(template="bookloantracker.templates.bookcadaster")
    def edit(self, id):
        book = Book.get(int(id))
        bookValues = {}
        bookValues["bookName"] = book.title
        bookValues["isbn"] = book.isbn
        bookValues["edition"] = book.edition
        bookValues["authors"] = book.authorStr
        bookValues["publisher"] = book.publisher.name
        bookValues["webPage"] = book.webPage
        bookValues["wordKeys"] = book.wordKeysStr
        bookValues["description"] = book.description
        bookValues["localization"] = book.localization
        bookValues["updateBook"] = book.id
        return dict(bookForm = bookForm,
                    values = bookValues)

    @expose()
    def save(self, **kw):
        if "bookName" in kw:
            self.populateSessionForm(**kw)
        if not "bookName" in session or not session["bookName"]:
            flash("Invalid request")
            redirect("index")

        log.debug("session['authors'] == %s" % session['authors'])
        authors = session["authors"].split(",")
        wordKeys = session["wordKeys"].split(",")
        authorList = self._getAuthorList(authors)
        publisher = self._getPublisher(session["publisher"])
        wordKeysList = self._getWordKeys(wordKeys)
        if int(session["updateBook"]) == 0:
            newBook = Book(title = session["bookName"],
                           isbn = session["isbn"],
                           edition = session["edition"],
                           description = session["description"],
                           webPage = session["webPage"],
                           localization = session["localization"],
                           publisher = publisher)
            log.debug("Adding authors: %s" % authorList)
            for author in authorList:
                newBook.addAuthor(author)
            for word in wordKeysList:
                word.addBook(newBook)
        else:
            book = Book.get(session["updateBook"])
            book.title = session["bookName"]
            book.isbn = session["isbn"]
            book.edition = session["edition"]
            book.description = session["description"]
            book.webPage = session["webPage"]
            book.localization = session["localization"]
            book.publisher = publisher
            # FIX-ME: remove everyone on and add everyone again is too ugly
            for a in book.authors:
                book.removeAuthor(a)
            for a in authorList:
                book.addAuthor(a)
            for w in wordKeysList:
                w.removeBook(book)
            for w in wordKeysList:
                w.addBook(book)
        flash(_("Book saved"))
        if session["updateBook"]:
            redirect("info",{"id":book.id})
        redirect("index")
        return {}

    @expose(template="bookloantracker.templates.bookinfo")
    def info(self, id):
        book = Book.get(id)
        log.debug("Returning book: %s" % book.title)
        return dict(bookInfoTable = bookInfoTable,
                    loanHistoryGrid = loanHistoryGrid,
                    book = book)

    def populateSessionForm(self, bookName, isbn, edition,
                            authors, publisher, webPage,
                            wordKeys, description, 
                            localization, updateBook):
        session["bookName"] = bookName
        session["isbn"] = isbn
        session["edition"] = edition
        session["authors"] = authors
        session["publisher"] = publisher
        session["webPage"] = webPage
        session["wordKeys"] = wordKeys
        session["description"] = description
        session["localization"] = localization
        session["updateBook"] = updateBook and int(updateBook) or 0

    def cleanSessionForm(self):
        session["bookName"] = None
        session["isbn"] = None
        session["edition"] = None
        session["authors"] = None
        session["publisher"] = None
        session["webPage"] = None
        session["wordKeys"] = None
        session["description"] = None
        session["localization"] = None
        session["updateBook"] = None

    def _getAuthorList(self, authors):
        authorList = []
        for author in authors:
            author = author.strip()
            authorDb = Author.select(LIKE(Author.q.name,author))
            if not authorDb.count():
                flash(_("I don't know this Author, please, give informations"))
                redirect("/authors/index",{"name":author,
                                           "ret":"books.save"})
            else:
                authorList.append(authorDb[0])
        return authorList

    def _getPublisher(self, publisherInStr):
        publisher = None
        if publisherInStr:
            publisher = publisherInStr.strip()
            publisherDb = Publisher.select(LIKE(Publisher.q.name,publisher))
            if not publisherDb.count():
                flash(_("I don't know this Publisher, please, give informations"))
                redirect("/publishers/index",{"name":publisher,
                                              "ret":"books.save"})
            publisher = publisherDb[0]
        return publisher

    def _getWordKeys(self, wordKeys):
        wordKeysList = []
        for word in wordKeys:
            word = word.strip()
            wordKeysDb = WordKeys.selectBy(word=word)
            if not wordKeysDb.count():
                bookWord = WordKeys(word=word)
            else:
                bookWord = wordKeysDb[0]
            wordKeysList.append(bookWord)
        return wordKeysList
